<template>
  <div class="user">
    <div class="user_box">
      <div>
        <img src="http://127.0.0.1:5000/head/login.jpg" alt="" />
        <button @click="show = false">没有账号，选择注册</button>
      </div>
      <div>
        <img src="http://127.0.0.1:5000/head/register.jpg" alt="" />
        <button @click="show = true">已有账号，直接登录</button>
      </div>

      <div class="user_content" :class="show ? '' : 'move'">
        <div class="user_login" v-if="show">
          <h2>欢迎登录</h2>
          <el-form
            :model="loginUser"
            status-icon
            :rules="loginRules"
            ref="loginFrom"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="邮箱" prop="email">
              <el-input
                type="email"
                v-model="loginUser.email"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                v-model="loginUser.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitLoginForm('loginFrom')"
                >登录</el-button
              >
            </el-form-item>
          </el-form>

          <span>忘了密码？</span>
        </div>
        <div class="user_register" v-if="!show">
          <h2>欢迎注册</h2>
          <el-form
            :model="registerUser"
            status-icon
            :rules="registerRules"
            ref="registerFrom"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="昵称" prop="name">
              <el-input
                type="text"
                v-model="registerUser.name"
                autocomplete="off"
                required
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input
                type="email"
                v-model="registerUser.email"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                type="password"
                v-model="registerUser.password"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitRegisterForm('registerFrom')"
                >注册</el-button
              >
              <el-button @click="resetForm('registerFrom')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jwt_decode from 'jwt-decode'
export default {
  name: 'User',
  data() {
    const validateName = (rule, value, callback) => {
      if (!this.registerUser.name.trim()) {
        callback(new Error('请输入用户名'))
      } else {
        const reg = /^.{2,10}$/
        reg.test(this.registerUser.name) ||
          callback(new Error('用户名长度是2-10位'))
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('请输入邮箱'))
      } else {
        const reg =
          /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
        reg.test(value) || callback(new Error('请输入正确的邮箱账号'))
        callback()
      }
    }

    const validatePass = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('请输入密码'))
      } else {
        const reg = /^[\w+$]{6,12}$/
        reg.test(value) ||
          callback(new Error('密码只能是6-12位的数字下划线和字母'))
        callback()
      }
    }
    return {
      registerUser: {
        name: '',
        password: '',
        email: '',
      },
      loginUser: {
        email: '',
        password: '',
      },
      registerRules: {
        name: [{ validator: validateName, trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
      },
      loginRules: {
        email: [{ validator: validateEmail, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
      },
      show: true,
    }
  },
  methods: {
    submitRegisterForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            uname: this.registerUser.name,
            uemail: this.registerUser.email,
            upassword: this.registerUser.password,
            uavater:
              'https://static.talkxj.com/photos/0bca52afdb2b9998132355d716390c9f.png',
          }
          this.$api.user
            .userRegister(data)
            .then((res) => {
              if (res.data.msg == '注册成功') {
                this.resetForm('registerFrom')
                this.show = true
                this.$message({
                  message: '恭喜你，注册成功',
                  type: 'success',
                })
              } else {
                this.$message.error('？？？注册怎么失败了')
              }
            })
            .catch((err) => {
              console.log(err)
              this.$message({
                message: '网页发生了错误！',
                type: 'error',
              })
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitLoginForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            uemail: this.loginUser.email,
            upassword: this.loginUser.password,
          }
          this.$api.user
            .userLogin(data)
            .then((res) => {
              if (res.data.code == 200) {
                // 设置token
                const { token } = res.data
                // console.log(token)
                // 存储到ls
                localStorage.setItem('eleToken', token)

                // 解析token
                const decode = jwt_decode(token)
                // console.log(decode)

                // token存储在vuex中
                this.$store.dispatch('setAuthorization', !this.isEmpty(decode))
                this.$store.dispatch('setUser', decode)
                this.resetForm('loginFrom')
                this.$message.success('恭喜你，登录成功')
                location.reload()
              } else if (res.data.code == 400) {
                this.$message.error('怎么密码错了？')
              } else {
                console.log(res.data.code)
                this.$message.error('还没注册吗？用户不存在啊')
              }
            })
            .catch((err) => {
              console.log(err)
              this.$message({
                message: '网页发生了错误！',
                type: 'error',
              })
            })
        } else {
          console.log(valid)
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === 'object' && Object.keys(value).length === 0) ||
        (typeof value === 'string' && value.trim().length === 0)
      )
    },
  },
}
</script>

<style lang="scss" scoped>
.user {
  position: fixed;
  left: 50%;
  top: 50%;
  height: 55%;
  width: 50%;
  // background-color: rgba(0, 0, 0, .4);
  z-index: 10000;
  // display: flex;
  // align-items: center;
  // justify-content: center;
  transform: translate(-50%, -50%);
  .user_box {
    height: 100%;
    width: 100%;
    min-height: 500px;
    background-color: #e8e8e8;
    display: flex;
    justify-content: space-between;
    position: relative;
    border-radius: 40px;
    overflow: hidden;
    z-index: 100;
    > div {
      position: relative;

      > img {
        height: 100%;
      }

      > button {
        position: absolute;
        margin: 2em 0;
        width: 70%;
        height: 12%;
        background: linear-gradient(
          90deg,
          #020024 0%,
          #085b9c 0%,
          #0c7b94 100%
        );
        border-radius: 2em;
        color: #fff;
        bottom: 0;
        font-weight: 600;
        left: 50%;
        transform: translateX(-50%);
        font-size: 1em;
      }
    }

    > div.user_content {
      position: absolute;
      height: 100%;
      width: 70%;
      background-color: #e8e8e8;
      transition: left 0.3s;
      left: 30%;
      > div {
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-evenly;

        > h2 {
          margin: 1em 0 0.5em;
          font-weight: 400;
          font-size: 2em;
        }

        > span {
          font-size: 1em;
          margin: 1em 0;
        }

        > button {
          margin: 1em 0;
          width: 30%;
          height: 12%;
          background: linear-gradient(
            90deg,
            #020024 0%,
            #085b9c 0%,
            #0c7b94 100%
          );
          border-radius: 2em;
          color: #fff;
          font-size: 1em;
          font-weight: 500;
        }
      }
    }
    .move {
      left: 0 !important;
    }
  }
}
</style>
